<!--  -->
<template>
  <div class="service">
    <Nav :title="title"></Nav>
    <!-- scroll -->
    <div class="srcoll-wrapper" ref="srcollWrapper">
      <Scroll
        :click="false"
        :tap="true"
        :pullup="true"
        :pulldown="true"
        :listenScroll="true"
        @scrollToEnd="scrollToEnd"
        :data.sync="serviceList"
        ref="myScroll"
      >
        <div>
          <ServiceList :serviceList.sync="serviceList"></ServiceList>
        </div>
      </Scroll>
    </div>
  </div>
</template>

<script>
import Nav from "../../components/Nav";
import Scroll from "../../components/Scroll";
import Page from "../../mixin/page";
import ServiceList from "../../components/ServiceList";
import { messageList } from "../../api/api";

export default {
  mixins: [Page],
  components: { Nav, Scroll, Page, ServiceList },
  data() {
    return {
      title: "客服",
      serviceList: [],
      reconnectTimer: null
    };
  },
  computed: {},
  watch: {},
  methods: {
    onMessage(event) {
      let res = JSON.parse(event.data);
      if (res.channel == "message_list") {
        let index = this.serviceList.findIndex(item => {
          return item.shop_id == res.data[0].shop_id;
        });
        index != -1 && this.serviceList.splice(index, 1, res.data[0]);
      }
    },
    _api() {
      messageList({ page: this.current_page + 1 }).then(
        ({ data: { result } }) => {
          if (result && result.length != 0) {
            this.serviceList = [...this.serviceList, ...result];
            this.current_page += 1;
            this.last_page = this.current_page + 1;
          } else {
            this.last_page = this.current_page;
          }
        }
      );
    },
    initWS() {
      window.socket.onclose = () => {
    
        clearInterval(this.reconnectTimer);
        this.reconnectTimer = null;
        this.reconnectTimer = setInterval(() => {
          if (window.socket.readyState == 1) {
            this.initWS();
            clearInterval(this.reconnectTimer);
            this.reconnectTimer = null;
          }
        }, 2000);  
      };
      window.socket.onerror = () => {
      
        clearInterval(this.reconnectTimer);
        this.reconnectTimer = null;
        this.reconnectTimer = setInterval(() => {
          if (window.socket.readyState == 1) {
            this.initWS();
            clearInterval(this.reconnectTimer);
            this.reconnectTimer = null;
          }
        }, 2000);
      };
      window.socket.onmessage = event => {
        this.onMessage(event);
      };
    }
  },
  created() {},
  mounted() {
    this._api();
    //websocket
    this.initWS();
  },
  updated() {}, //生命周期 - 更新之后
  destroyed() {
    clearInterval(this.reconnectTimer);
    this.reconnectTimer = null;
  } //生命周期 - 销毁完成
};
</script>
<style lang='less' scoped>
//@import url(); 引入公共css类
.service {
  height: 100%;
}
.srcoll-wrapper {
  height: calc(100% - 45px);
  overflow: hidden;
}
</style>